import { getDict } from '@/api/sys/dict'
import { ICommonState, ICtx, IDictKeyV, IDictType, IPageTab } from '@/typings'
import { TOGGLE_LOADING, SET_DICT_BY_KEY, SET_ROUTER, DEL_ROUTER } from './actionTypes'

const actions = {
  // 全局loading
  toggleLoading({ commit }: ICtx<ICommonState>, payload?: boolean): void {
    commit(TOGGLE_LOADING, !!payload)
  },
  // 字典获取
  getDictByKey({ commit, state }: ICtx<ICommonState>, key: string): Promise<Array<IDictType>> {
    return new Promise((resolve) => {
      if (state.dictData.has(key)) {
        resolve(state.dictData.get(key))
      }
      getDict(key).then((res) => {
        const dictVal: Array<IDictType> = res.result
        commit(SET_DICT_BY_KEY, { key, value: dictVal } as IDictKeyV)
        resolve(dictVal)
      })
    })
  },
  // 设置tabs菜单
  setRouter({ commit }: ICtx<ICommonState>, payload: IPageTab): void {
    commit(SET_ROUTER, payload)
  },
  // 删除tabs菜单
  delRouter({ commit }: ICtx<ICommonState>, key: string): void {
    commit(DEL_ROUTER, key)
  }
}

export default actions
